package com.zhima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhima.entity.OjQuestion;
import com.zhima.entity.OjQuestionAudit;
import com.zhima.enums.QuestionAuditState;
import com.zhima.exception.ZhimaOjException;
import com.zhima.feignclient.LocalTaskFeignClient;
import com.zhima.mapper.OjQuestionAuditMapper;
import com.zhima.properties.ZhimaQuestionProperties;
import com.zhima.service.OjQuestionAuditService;
import com.zhima.service.OjQuestionService;
import com.zhima.util.AuthorizationUtil;
import com.zhima.util.PageUtil;
import com.zhima.vo.QuestionAuditVO;
import com.zhima.vo.QuestionPublishDetailVO;
import com.zhima.vo.SimpleQuestionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.zhima.constant.QuestionXxlJobConstant.AUDIT_QUESTION;
import static com.zhima.exception.ErrorCode.NOT_ALLOW_COVER_AUDIT;
import static com.zhima.exception.ErrorCode.TEST_CASES_NOT_ALLOW_EMPTY;

@Service
public class OjQuestionAuditServiceImpl extends ServiceImpl<OjQuestionAuditMapper, OjQuestionAudit> implements OjQuestionAuditService {
    @Autowired
    private OjQuestionService ojQuestionService;

    @Autowired
    private ZhimaQuestionProperties zhimaQuestionProperties;

    @Autowired
    private LocalTaskFeignClient localTaskFeignClient;

    @Override
    public boolean submitAuditQuestion(Long userId, Long questionId) {
        OjQuestion ojQuestion = ojQuestionService.lambdaQuery().eq(OjQuestion::getId, questionId).one();
        AuthorizationUtil.isLoginUserResource(userId, ojQuestion.getUploaderId());
        OjQuestionAudit ojQuestionAudit = lambdaQuery().eq(OjQuestionAudit::getId, questionId).one();
        // 上一次的审核还没结束，并且不允许覆盖上一次的审核
        if (ojQuestionAudit != null && ojQuestionAudit.getState() == QuestionAuditState.AUDITING && !zhimaQuestionProperties.isAllowCoverAudit()) {
            throw new ZhimaOjException(NOT_ALLOW_COVER_AUDIT);
        }
        // 测评点信息不允许为空
        if (ojQuestion.getTestCaseTemplates() == null || ojQuestion.getTestCaseTemplates().isEmpty()) {
            throw new ZhimaOjException(TEST_CASES_NOT_ALLOW_EMPTY);
        }
        ojQuestionAudit = BeanUtil.copyProperties(ojQuestion, OjQuestionAudit.class);
        // 覆盖之前失败的审核
        // 将状态重置
        ojQuestionAudit.setState(QuestionAuditState.AUDITING);
        // 将修改建议制空
        ojQuestionAudit.setAdvice(null);
        return saveOrUpdate(ojQuestionAudit) && localTaskFeignClient.publishTask(AUDIT_QUESTION, List.of(String.valueOf(questionId)));
    }

    @Override
    public boolean auditQuestion(Long questionId, String advice) {
        return lambdaUpdate()
                .eq(OjQuestionAudit::getId, questionId)
                .set(OjQuestionAudit::getState, StrUtil.isBlank(advice) ? QuestionAuditState.PASS_AUDIT : QuestionAuditState.NOT_PASS_AUDIT)
                .set(OjQuestionAudit::getAdvice, advice)
                .set(OjQuestionAudit::getAuditTime, new Date()).update();
    }

    @Override
    public Page<QuestionAuditVO> pageQueryQuestionAudit(Long userId, Long pageNum, Long pageSize, boolean onlyPassing) {
        Page<OjQuestionAudit> pageQueryResult = page(new Page<>(pageNum - 1, pageSize), new LambdaQueryWrapper<OjQuestionAudit>()
                .eq(userId != null, OjQuestionAudit::getUploaderId, userId)
                // onlyPassing-》true只要处在审核中的记录
                .eq(onlyPassing, OjQuestionAudit::getState, QuestionAuditState.AUDITING)
        );
        return PageUtil.buildPage(pageQueryResult, pageQueryResult.getRecords().stream().map(r -> BeanUtil.copyProperties(r, QuestionAuditVO.class)).collect(Collectors.toList()));
    }

    @Override
    public List<SimpleQuestionVO> batchQuerySimpleQuestionByIds(List<Long> questionIds) {
        if (questionIds.isEmpty()) {
            return Collections.emptyList();
        }
        return lambdaQuery()
                .in(OjQuestionAudit::getId, questionIds)
                .select(OjQuestionAudit::getId, OjQuestionAudit::getPrefix, OjQuestionAudit::getNumber, OjQuestionAudit::getTitle, OjQuestionAudit::getDifficulty)
                .list()
                .stream().map(r -> BeanUtil.copyProperties(r, SimpleQuestionVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public boolean updateAuditState(long questionAuditId, QuestionAuditState questionAuditState) {
        return lambdaUpdate().eq(OjQuestionAudit::getId, questionAuditId).set(OjQuestionAudit::getState, questionAuditState).update();
    }

    @Override
    public QuestionPublishDetailVO queryQuestionDetailById(Long userId, Long questionId) {
        OjQuestionAudit questionAudit = getById(questionId);
        QuestionPublishDetailVO questionPublishDetailVO = BeanUtil.copyProperties(questionAudit, QuestionPublishDetailVO.class);
        questionPublishDetailVO.setIsSelf(questionPublishDetailVO.getUploaderId().equals(userId));
        return questionPublishDetailVO;
    }

    @Override
    public boolean cancelSubmitQuestionAudit(Long questionId) {
        return removeById(questionId);
    }
}
